using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesFileManager : System.Web.UI.Page
{
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataObj CurPageDataObj = new DataObj();
    protected bool ReadOnly = false;

    #region ClaimInternalID
    protected string ClaimInternalID
    {
        get
        {
            return ViewState["ClaimInternalID"].ToString();
        }

        set
        {
            ViewState["ClaimInternalID"] = value;
        }
    }

    #endregion

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #region SelectLink
    protected string SelectLink
    {
        get
        {
            //return ViewState["MandatoryMessage"].ToString();
            string text = (string)ViewState["SelectLink"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["SelectLink"] = value;
        }
    }
    #endregion

    #region DeleteLink
    protected string DeleteLink
    {
        get
        {
            string text = (string)ViewState["DeleteLink"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["DeleteLink"] = value;
        }
    }
    #endregion

    #region ConfirmMessage
    protected string ConfirmMessage
    {
        get
        {
            string text = (string)ViewState["ConfirmMessage"];
            if (text != null)
                return text;
            else
                return string.Empty;
        }

        set
        {
            ViewState["ConfirmMessage"] = value;
        }
    }
    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        this.DataDelete();

        this.Table_MessageBox.Visible = false;

        if (!IsPostBack)
        {
            #region Request.QueryString["id"]

            if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
            {
                this.ClaimInternalID = Request.QueryString["id"];
            }
            else
            {
                Response.Redirect(GonzalesErrorPageRedirect.PageFlowError);
            }

            #endregion

            
            if (Request.QueryString["NoEdit"] != null && Request.QueryString["NoEdit"].CompareTo("1") == 0)
            {
                this.ReadOnly = true;
            }
            

            this.SwitchLanguage();
            this.PageComponentSetup();

            this.LoadData();

            if (this.ResultTable != null)
            {
                DataView ResultView = new DataView(this.ResultTable);
                ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                this.BindData(ResultView);
            }
        }
    }

    protected void Button_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.FileUploadSource.PostedFile != null && this.FileUploadSource.PostedFile.FileName.Length > 0)
            {
                SupportingDocument NewDoc = new SupportingDocument(
                    SwissArmy.UniqueID(),
                    this.FileUploadSource.PostedFile.FileName);

                int FileLength = this.FileUploadSource.PostedFile.ContentLength;

                NewDoc.BufferContent = new byte[FileLength];

                Stream FileStreamObj = null;
                FileStreamObj = this.FileUploadSource.PostedFile.InputStream;
                FileStreamObj.Read(NewDoc.BufferContent, 0, FileLength);

                //   NewDoc.FileType = this.FileUploadSource.PostedFile.FileName.Substring(this.FileUploadSource.PostedFile.FileName.Length - 3);
                string[] file = this.FileUploadSource.PostedFile.FileName.Split(new char[] { '.' });
                NewDoc.FileType = file[file.Length - 1].ToString();

                using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
                {
                    if (CurFileManager.UploadNewFile(NewDoc, this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID))
                    {
                        this.LoadData();

                        if (this.ResultTable != null)
                        {
                            DataView ResultView = new DataView(this.ResultTable);
                            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                            this.BindData(ResultView);
                        }
                    }
                    else
                    {
                        string LogID = SwissArmy.UniqueID();
                        this.CurLogManager.LogError(LogID, "[GonzalesFileManager.Button_Upload_Click] : Failed at CurFileManager.UploadNewFile : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                        this.ShowErrorMessage("Error! " + LogID);
                    }
                }

                // update total file
                try
                {
                    int CurrentTotalFiles = Int32.Parse(this.HiddenField_TotalFiles.Value);
                    this.HiddenField_TotalFiles.Value = (CurrentTotalFiles++).ToString();
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
            else
            {
                this.ShowErrorMessage("Invalid File");
            }
        }
        catch (Exception)
        {
            // do nothing
        }
    }

    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView);
        }
    }

    protected void DropDownList_SortOrder_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.DropDownList_SortBy_SelectedIndexChanged(sender, e);
    }

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.GridViewHeader.Count; i++)
            {
                cells[i].Text = this.GridViewHeader[i].ToString();
            }
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        this.Button_Cancel.Attributes["onclick"] = "parent.ModalWindow.hide();return false;";
        this.Button_Cancel2.Attributes["onclick"] = "parent.ModalWindow.hide();return false;";

        if (this.ReadOnly)
        {
            this.Table_FileUpload.Visible = false;
            this.Button_Cancel2.Visible = true;
            this.GridViewResult.Columns[5].Visible = false;
        }

    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_SupportDocument.Text = CurLanguageFactory.DisplayValue("SupportDocument");
                this.Label_Title.Text = CurLanguageFactory.DisplayValue("Title");

                this.Button_Cancel.Text = CurLanguageFactory.DisplayValue("Cancel");
                this.Button_Cancel2.Text = CurLanguageFactory.DisplayValue("Cancel2");
                this.Button_Upload.Text = CurLanguageFactory.DisplayValue("Upload");
                this.SelectLink = CurLanguageFactory.DisplayValue("SelectLink");
                this.DeleteLink = CurLanguageFactory.DisplayValue("DeleteLink");
                this.ConfirmMessage = CurLanguageFactory.DisplayValue("ConfirmMessage");

                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("FileName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("FileType"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("UploadDateInStr"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("UploadedBy"));

                // sort order
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("FileName"), this.CurPageDataObj.FileName));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("FileType"), this.CurPageDataObj.FileType));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("UploadDateInStr"), this.CurPageDataObj.UploadDate));

                // sort by
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));

            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesClaimsPendingForAuthorizedDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData

    protected void LoadData()
    {
        using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
        {
            SupportingDocuments ResultDocuments = CurFileManager.GetFilesByClaimID(this.ClaimInternalID);

            if (ResultDocuments != null)
            {
                this.HiddenField_TotalFiles.Value = ResultDocuments.Count.ToString();

                this.ResultTable = new DataTable();
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.InternalID, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.FileName, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.FileType, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadDate, Type.GetType("System.DateTime")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadDateInStr, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.UploadedBy, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.SelectLink, Type.GetType("System.String")));
                this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DeleteLink, Type.GetType("System.String")));

                foreach (SupportingDocument ResultDoc in ResultDocuments)
                {
                    DataRow ResultRow = this.ResultTable.NewRow();

                    ResultRow[this.CurPageDataObj.InternalID] = ResultDoc.InternalID;
                    string[] filename = SwissArmy.StringSplit(ResultDoc.FileName, "\\");

                    ResultRow[this.CurPageDataObj.FileName] = filename[filename.Length -1].ToString();
                    ResultRow[this.CurPageDataObj.FileType] = ResultDoc.FileType;
                    ResultRow[this.CurPageDataObj.UploadDate] = ResultDoc.UploadDate;
                    ResultRow[this.CurPageDataObj.UploadDateInStr] = SwissArmy.DateConvert(ResultDoc.UploadDate, this.CurrentPrivateSession.DateFormatInUse, "/");
                    ResultRow[this.CurPageDataObj.UploadedBy] = ResultDoc.UploadedBy.DisplayName + " (" + ResultDoc.UploadedBy.EmailID + ") ";
                    ResultRow[this.CurPageDataObj.SelectLink] = "<a href='GonzalesViewFile.aspx?id=" + ResultDoc.InternalID + "' target='newdoc' class='GridViewLink'>"+ this.SelectLink +"</a>";
                    ResultRow[this.CurPageDataObj.DeleteLink] = "<a href='GonzalesFileManager.aspx?id=" + this.ClaimInternalID + "&did=" + ResultDoc.InternalID + "&DELETE=TRUE' class='GridViewLink' onclick=\"return confirm('" + this.ConfirmMessage + "')\">" + this.DeleteLink + "</a>";

                    this.ResultTable.Rows.Add(ResultRow);
                }

            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesFileManager.LoadData] : CurFileManager.GetFilesByClaimID('" + this.ClaimInternalID + "') : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("Error! " + LogID);
            }

        }
    }

    #endregion

    #region DataDelete

    protected void DataDelete()
    {
        if (Request.QueryString["DELETE"] != null && Request.QueryString["DELETE"].CompareTo("TRUE") == 0 &&
            Request.QueryString["did"] != null && Request.QueryString["did"].Length == 36 &&
            Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36            
            )
        {
            bool smooth = true;

            using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
            {
                if (!(smooth = CurFileManager.DeleteFile(Request.QueryString["did"])))
                {
                    string ErrorID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(ErrorID, "", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage("Error: " + ErrorID);
                }
            }

            if (smooth)
            {
                Response.Redirect("GonzalesFileManager.aspx?id=" + Request.QueryString["id"]);
            }
        }
    }

    #endregion

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #region Class: DataObj

    protected class DataObj
    {
        public readonly string InternalID = "InternalID";
        public readonly string FileName = "FileName";
        public readonly string FileType = "FileType";
        public readonly string UploadDate = "UploadDate";
        public readonly string UploadDateInStr = "UploadDateInStr";
        public readonly string UploadedBy = "UploadedBy";
        public readonly string SelectLink = "SelectLink";
        public readonly string DeleteLink = "DeleteLink";
    }

    #endregion
}
